package main;

import java.util.Observable;
import java.util.Observer;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableModelListener;

import aisLogic.Manager;
import aisLogic.Module;

public class AISTable extends JTable implements Observer, TableModelListener {
	
	
	public AISTable(){
		super(new AISTableModel());
		AthenaMain.manager.addObserver(this);
		getModel().addTableModelListener(this);
		setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		getSelectionModel().addListSelectionListener(new AISSelectionListener());
		getTableHeader().setReorderingAllowed(false);
	}
	
	public void update(Observable o, Object arg) {
		Object[] objs = (Object[])arg;
		int action = ((Integer)objs[Manager.ACTION]).intValue();
		int row = getSelectedRow();
		int row_count = getRowCount();
		
		switch(action){
			case Manager.MODULE_ADD:
				((AISTableModel) getModel()).addRow(getModuleData(objs[Manager.OBJECT]));
				setRowSelectionInterval(row_count, row_count);
				break;
			case Manager.MODULE_REMOVE:
				if(row != -1){
					removeRowSelectionInterval(row, row);
					((AISTableModel) getModel()).removeRow(row);
				} else {
					((AISTableModel) getModel()).removeRow(row_count - 1);
				}
				break;
			case Manager.MODULE_DOWN:
				((AISTableModel) getModel()).moveRow(row, false);
				setRowSelectionInterval(row + 1, row + 1);
				break;
			case Manager.MODULE_UP:
				((AISTableModel) getModel()).moveRow(row, true);
				setRowSelectionInterval(row - 1, row - 1);
				break;
		}
		updateUI();
	}
	
	public Object[] getModuleData(Object o){
		Object []obj = new Object[((AISTableModel)getModel()).getColumnCount()];
		obj[0] = AthenaMain.manager.getModuleId((Module) o);
		obj[Module.ATT_X] = ((Module)o).getX();
		obj[Module.ATT_Y] = ((Module)o).getY();
		obj[Module.ATT_WIDTH] = ((Module)o).getWidth();
		obj[Module.ATT_HEIGHT] = ((Module)o).getHeight();
		obj[Module.ATT_MISC] = ((Module)o).getMisc();
		return obj;
	}

	public void moduleSelected(int index) {
		if(index == -1){
			return;
		}
		Module module = AthenaMain.manager.getModule(index);
		AthenaMain.uinterface.canvasScrollPane.getImagePanel().setSelectedRect(module);
	}
}
